package com.mrjoew.weekend.configurations;

import com.mrjoew.weekend.services.sys.SysRoleService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author Christopher Jones
 * @ClassName ResourceServerConfig
 * @explain 资源服务鉴权配置
 * @date 2020/6/17 0017 21:30
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final JwtAccessTokenConverter accessTokenConverter;

    private final SysRoleService sysRoleService;

    public ResourceServerConfiguration(JwtAccessTokenConverter accessTokenConverter, SysRoleService sysRoleService) {
        this.accessTokenConverter = accessTokenConverter;
        this.sysRoleService = sysRoleService;
    }

    @Value("${spring.application.name}")
    private String resourceId;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                // 标记该资源服务器 resourceId
                .resourceId(resourceId)
                // 设置 Token Converter
                .tokenStore(new JwtTokenStore(accessTokenConverter))
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and().requestMatchers().anyRequest()
                .and().authorizeRequests()
                // 获取所有匿名访问
                .antMatchers(sysRoleService.anonymous()).permitAll()
                .anyRequest().authenticated();
    }
}
